﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Evan.Model
{
    /// <summary>
    /// DynamicModel 转换类   转换Json数据为dynamic , 使用了 Newtonsoft.Json 
    /// </summary>
    public static class ConvertModel
    {
        /// <summary>
        /// 将动态list转为json字符串
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ConvertDynamicListToJson(List<dynamic> list)
        {
            ArrayList arr = new ArrayList();
            foreach (var item in list)
            {
                arr.Add(ConvertToJson(item));
            }
            string jsonStr = string.Join(",", arr.ToArray());
            if (string.IsNullOrEmpty(jsonStr))
            {
                jsonStr = "[{}]";
            }
            else
            {
                jsonStr = "[" + jsonStr + "]";
            }
            return jsonStr;
        }
        /// <summary>
        /// 将Json 转换为 dynamic 不支持嵌套
        /// </summary>
        /// <param name="JsonStr"></param>
        /// <returns></returns>
        public static dynamic ConvertToDynamic(string JsonStr)
        {
            try
            {
                dynamic Model = new DynamicModel();
                JsonReader reader = new JsonTextReader(new StringReader(JsonStr));
                object _temp = null;
                string[] _valuetype = { "String" }; //目前只有string需要替换
                string _value = "";
                while (reader.Read())
                {
                    if (reader.TokenType.ToString() != "StartObject" && reader.TokenType.ToString() != "EndObject")
                    {
                        if (reader.TokenType.ToString() == "PropertyName") //属性
                        {
                            _temp = reader.Value; //缓存属性
                        }
                        else //值 
                        {
                            if (_valuetype.Contains(reader.ValueType.Name, StringComparer.OrdinalIgnoreCase)) //需要将String里面的字符检查是否有编码
                            {
                                //if (reader.Value.ToString().StartsWith("_FLAG_CONTENT_ENCODE_")) // 需要解码
                                //{
                                //    _value = reader.Value.ToString().Replace("_FLAG_CONTENT_ENCODE_", "");
                                //    _value = Common.CodeConvert.DeCode(_value);
                                //    Model.Set(_temp, _value); //解码后赋值
                                //}
                                //else
                                //{
                                //    Model.Set(_temp, reader.Value); //正常赋值
                                //}
                                _value = Common.TransCode.StrDeCode(reader.Value.ToString());
                                Model.Set(_temp, _value); //解码后赋值
                            }
                            else
                            {
                                Model.Set(_temp, reader.Value); //正常赋值
                            }
                            _temp = null;
                        }
                    }
                }
                return Model;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 将Dic转换为Dynamic
        /// </summary>
        /// <param name="Dic"></param>
        /// <returns></returns>
        public static dynamic ConvertToDynamic(Dictionary<string, object> Dic)
        {
            try
            {
                dynamic Model = new DynamicModel();

                if (Dic != null)
                {
                    //直接遍历
                    foreach (var item in Dic)
                    {
                        Model.Set(item.Key, item.Value);
                    }
                }
                return Model;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 将 DynamicModel 转换为json  不支持嵌套对象 
        /// </summary>
        /// <param name="Model"></param>
        /// <returns></returns>
        public static string ConvertToJson(DynamicModel Model)
        {
            if (Model != null)
            {
                string JsonStr = "{";
                foreach (var property in (Dictionary<string, object>)Model._Map_In_Dictionary)
                {
                    if (property.Value.GetType().ToString() == "System.String")
                    {
                        
                        JsonStr += "\"" + property.Key + "\":\"" + Common.TransCode.StrEnCode(property.Value.ToString())+ "\",";
                    }
                    else
                    {
                        JsonStr += "\"" + property.Key + "\":\"" + property.Value + "\",";
                    }
                }
                JsonStr = JsonStr.TrimEnd(',');
                JsonStr += "}";
                return JsonStr;
            }
            else
            {
                return "{}";
            }
        }

        public static Model.SysModel.FieldModel ConvertToFieldModel(DynamicModel Model,string TableName)
        {
            SysModel.FieldModel FieldModel = new SysModel.FieldModel();
            Dictionary<string, object> ModelDic = ConvertToDictionary(Model);
            FieldModel.TableName = TableName;

            FieldModel.FieldType = "";
            FieldModel.FieldDefault = "";

            switch (ModelDic["FieldType"].ToString().ToLower())
            {
                case "input":
                case "password":
                case "textarea":
                case "radio":
                case "checkbox":
                case "select":
                case "multipleselect":
                case "fileupload":
                case "imgupload":
                    FieldModel.FieldType = "nvarchar";
                    break;
                case "time":
                    FieldModel.FieldType = "datetime";
                    break;
                case "switch":
                    FieldModel.FieldType = "int";
                    break;
                case "multipleimgupload":
                case "editor":
                    FieldModel.FieldType = "nvarchar-max";
                    
                    break;
                default:
                    FieldModel.FieldType = "nvarchar-max";
                    break;
            }
            FieldModel.FieldDefault = "";
            FieldModel.FieldName = ModelDic["FieldName"].ToString();

            FieldModel.FieldLength = 4000;
            return FieldModel;
        }

        /// <summary>
        /// 将 DynamicModel 转换为 Dictionary 支持 Dictionary[key]取值 解决调用数据库的时候字段与系统字段一致的问题
        /// </summary>
        /// <param name="Model"></param>
        /// <returns></returns>
        public static Dictionary<string, object> ConvertToDictionary(DynamicModel Model)
        {
            return (Dictionary<string, object>)Model._Map_In_Dictionary;
        }

        public static Model.SysModel.FieldModel ConvertToFieldModel(Model.SysModel.TemplateFieldModel TemplateFieldModel, string TableName)
        {
            SysModel.FieldModel FieldModel = new SysModel.FieldModel();
            FieldModel.TableName = TableName;
            FieldModel.FieldType = "";
            FieldModel.FieldDefault = "";
            switch (TemplateFieldModel.FieldType)
            {
                case "input":
                case "password":
                case "textarea":
                case "radio":
                case "checkbox":
                case "select":
                case "multipleselect":
                case "fileupload":
                case "imgupload":
                    FieldModel.FieldType = "nvarchar";
                    break;
                case "time":
                    FieldModel.FieldType = "datetime";
                    break;
                case "switch":
                    FieldModel.FieldType = "int";
                    break;
                case "multipleimgupload":
                case "editor":
                    FieldModel.FieldType = "ntext";
                    break;
                default:
                    FieldModel.FieldType = "nvarchar";
                    break;
            }
            FieldModel.FieldName = TemplateFieldModel.FieldName;
            FieldModel.FieldLength = int.Parse(TemplateFieldModel.FieldSize);
            FieldModel.FieldDefault = "";
            return FieldModel;

        }

        /// <summary>
        /// 指定的Dynamic中是否有对应的值
        /// </summary>
        /// <param name="Model">传入动态Model</param>
        /// <param name="Key">传入的Key </param>
        /// <returns>传入的Key是否在Model中存在 true 存在  false 不存在</returns>
        public static bool HasKey(dynamic Model, string Key)
        {
            if (Model == null)
            {
                return false;
            }
            else
            {
                return ((Dictionary<string, object>)Model._Map_In_Dictionary).ContainsKey(Key);
            }
        }

    }
}
